package com.china08.yxyapi.api.manage.tec.teaching.lecture.teachreport;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.esbag.test.YxyEsbagTeachingTestQuesStu;
import com.china08.yxyapi.entity.mg.res.AllTemplate;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Branch;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Sub;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.esbag.YxyEsbagTeachingTestQuesStuRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.china08.yxyapi.service.manage.tec.teaching.lecture.LectureQuestionService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * 老师 ---备授课--授课报告-测验报告--查看报告--单选题
 * 
 */
@CrossOrigin
@RestController
public class LectureReportClassTestReportDetailController extends YxyApiBaseController {

    @Autowired
    private YxyEsbagTeachingTestQuesStuRepository yxyEsbagTeachingTestQuesStuRepository;

    @Autowired
    private LectureQuestionService lectureQuestionService;

    @Autowired
    private ElasticQuesService elasticService;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/testreport/detail/class/sch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<RespModel> process(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = false) ReqModel reqModel)
                    throws JsonParseException, JsonMappingException, IOException {

        String id = reqModel.id;
        String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();
        Assert.notNull(StringUtils.defaultIfBlank(id, null), "授课包ID为空");
        String quesGroupId = reqModel.quesGroupId;
        String classId = reqModel.classId;
        List<RespModel> respModels = new ArrayList<RespModel>();
        Assert.notNull(StringUtils.defaultIfBlank(quesGroupId, null), "题组ID为空");
        List<YxyEsbagTeachingTestQuesStu> list = yxyEsbagTeachingTestQuesStuRepository
                .findByTeacherIdAndSchoolIdAndPackIdAndQuesGroupIdAndClassId(userId, schoolId, id, quesGroupId,
                        classId);
        // 根据试题ID进行分组取出共多少道试题
        Map<String, List<YxyEsbagTeachingTestQuesStu>> map = list.stream()
                .collect(Collectors.groupingBy(YxyEsbagTeachingTestQuesStu::getQuesId));

        List<String> quesIds = new ArrayList<String>();
        for (String key : map.keySet()) {
            quesIds.add(key);// 把试题放入集合中
        }
        List<String> danQues = new ArrayList<String>();
        List<String> duoQues = new ArrayList<String>();
        List<String> tianQues = new ArrayList<String>();
        List<String> jieQues = new ArrayList<String>();
        for (String quesId : quesIds) {
            ElasticYxyYxyQuesResource findByEsQuesId = elasticService.findByEsQuesId(quesId);
            if (findByEsQuesId.getQuestionType().equals("1")) {
                danQues.add(findByEsQuesId.getId());
            } else if (findByEsQuesId.getQuestionType().equals("8")) {
                duoQues.add(findByEsQuesId.getId());
            } else if (findByEsQuesId.getQuestionType().equals("2")) {
                tianQues.add(findByEsQuesId.getId());
            } else {
                jieQues.add(findByEsQuesId.getId());
            }
        }
        List<String> queStrings = new ArrayList<String>();
        for (String string : danQues) {
            queStrings.add(string);
        }
        for (String string : duoQues) {
            queStrings.add(string);
        }
        for (String string : tianQues) {
            queStrings.add(string);
        }
        for (String string : jieQues) {
            queStrings.add(string);
        }

        for (String quesId : queStrings) {
            RespModel model = new RespModel();
            ElasticYxyYxyQuesResource findByEsQuesId = lectureQuestionService.findByEsQuesId(quesId);
            // 题干 + 正确答案
            model.quesId = quesId;
            model.quesBody = findByEsQuesId.getQuesBody();
            model.difficultyLevel = findByEsQuesId.getDifficultyLevel();
            model.knowledgeTexts = findByEsQuesId.getKnowledgeTexts();
            model.questionType = findByEsQuesId.getQuestionType();
            // 单选题
            if (findByEsQuesId.getQuestionType().equals("1")) {

                Integer rateForGet = 0;
                Double rateForAll = 0d;

                // 获取每道试题对应参数
                for (YxyEsbagTeachingTestQuesStu testQuesStu : list) {
                    if (testQuesStu.getQuesId().equals(quesId)) {
                        rateForGet += testQuesStu.getRightRate();
                        rateForAll += 100;
                    }
                }
                if (rateForAll != 0) {
                    double rate = (rateForGet / rateForAll) * 100;
                    BigDecimal b = new BigDecimal(rate);
                    double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    model.rate = f1;
                } else {
                    model.rate = 0.0;
                }

                // 单选题答案
                List<String> ansList = new ArrayList<String>();

                AllTemplate allTemplate = (AllTemplate) findByEsQuesId.getQuesBody();
                Sub sub = allTemplate.sub;
                List<Branch> branch = sub.branch;
                for (Branch branch2 : branch) {
                    ansList.add(branch2.no);
                }
                model.singleAnswer = ansList;
                // 答案对应学生人数
                // List<Integer> ansCountList = new ArrayList<Integer>();
                List<YxyEsbagTeachingTestQuesStu> list2 = map.get(quesId);
                for (YxyEsbagTeachingTestQuesStu quesStu : list2) {
                    if (null == quesStu.getAnswerOfMy()) {
                        quesStu.setAnswerOfMy("未作答");
                    }
                }
                // 答案对应学生信息
                Map<String, List<YxyEsbagTeachingTestQuesStu>> mapstu = list2.stream()
                        .collect(Collectors.groupingBy(YxyEsbagTeachingTestQuesStu::getAnswerOfMy));

                Map<String, List<Student>> mapSingle = new HashMap<String, List<Student>>();
                for (String answer : ansList) {
                    List<YxyEsbagTeachingTestQuesStu> listStudent = mapstu.get(answer);
                    List<Student> students = new ArrayList<Student>();
                    Student student = null;
                    if (CollectionUtils.isNotEmpty(listStudent)) {
                        for (YxyEsbagTeachingTestQuesStu yxyEsbagTeachingTestQuesStu : listStudent) {
                            student = new Student();
                            student.studentId = yxyEsbagTeachingTestQuesStu.getStudentId();
                            student.studentName = yxyEsbagTeachingTestQuesStu.getStudentNick();
                            students.add(student);
                        }
                    }
                    mapSingle.put(answer, students);
                }
                model.singleMap = mapSingle;

            }

            // 多选题
            if (findByEsQuesId.getQuestionType().equals("8")) {

                Integer rateForGet = 0;
                Double rateForAll = 0d;

                // 获取每道试题对应参数
                for (YxyEsbagTeachingTestQuesStu testQuesStu : list) {
                    if (testQuesStu.getQuesId().equals(quesId)) {
                        rateForGet += testQuesStu.getRightRate();
                        rateForAll += 100;
                    }
                }
                if (rateForAll != 0) {
                    double rate = (rateForGet / rateForAll) * 100;
                    BigDecimal b = new BigDecimal(rate);
                    double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    model.rate = f1;
                } else {
                    model.rate = 0.0;
                }

                // 多选题答案
                List<String> bnsList = new ArrayList<String>();

                AllTemplate allTemplate = (AllTemplate) findByEsQuesId.getQuesBody();
                Sub sub = allTemplate.sub;
                List<Branch> branch = sub.branch;
                for (Branch branch2 : branch) {
                    bnsList.add(branch2.no);
                }
                model.multiAnswer = bnsList;
                // 答案对应学生人数
                List<YxyEsbagTeachingTestQuesStu> list2 = map.get(quesId);
                for (YxyEsbagTeachingTestQuesStu quesStu : list2) {
                    if (null == quesStu.getAnswerOfMy()) {
                        quesStu.setAnswerOfMy("未作答");
                    }
                }
                // 答案对应学生信息
                Map<String, List<YxyEsbagTeachingTestQuesStu>> bmapstu = list2.stream()
                        .collect(Collectors.groupingBy(YxyEsbagTeachingTestQuesStu::getAnswerOfMy));

                Map<String, List<YxyEsbagTeachingTestQuesStu>> bmapstunewMap = new HashMap<String, List<YxyEsbagTeachingTestQuesStu>>();
                for (String myanswer : bmapstu.keySet()) {
                    List<YxyEsbagTeachingTestQuesStu> valueList = bmapstu.get(myanswer);
                    if (!myanswer.equals("未作答") && myanswer.length() > 1) {
                        String[] split = myanswer.split(",");
                        for (String string : split) {
                            bmapstunewMap.put(string, valueList);
                        }
                    }
                    bmapstunewMap.put(myanswer, valueList);
                }
                // 多选学生的作答信息（key - value 对应）
                Map<String, List<Student>> mapMulti = new HashMap<String, List<Student>>();
                for (String answer : bnsList) {
                    List<YxyEsbagTeachingTestQuesStu> listStudent = bmapstunewMap.get(answer);
                    List<Student> students = new ArrayList<Student>();
                    Student student = null;
                    if (CollectionUtils.isNotEmpty(listStudent)) {
                        for (YxyEsbagTeachingTestQuesStu yxyEsbagTeachingTestQuesStu : listStudent) {
                            student = new Student();
                            student.studentId = yxyEsbagTeachingTestQuesStu.getStudentId();
                            student.studentName = yxyEsbagTeachingTestQuesStu.getStudentNick();
                            students.add(student);
                        }
                    }
                    mapMulti.put(answer, students);
                }
                model.multiMap = mapMulti;

            }

            // 填空题
            if (!findByEsQuesId.getQuestionType().equals("1") && !findByEsQuesId.getQuestionType().equals("8")) {
                // 填空题评分
                List<Integer> cnsList = new ArrayList<Integer>();
                cnsList.add(5);
                cnsList.add(4);
                cnsList.add(3);
                cnsList.add(2);
                cnsList.add(1);
                cnsList.add(0);
                cnsList.add(-1);
                model.blankMark = cnsList;
                List<YxyEsbagTeachingTestQuesStu> list3 = map.get(quesId);
                for (YxyEsbagTeachingTestQuesStu quesStu : list3) {
                    // zhiyao 未批閱
                    if (quesStu.getIsReadOver() == 0) {
                        quesStu.setMark(-1);
                    } else if (null == quesStu.getMark()) {
                        quesStu.setMark(-2);
                    }
                }

                Map<Integer, List<YxyEsbagTeachingTestQuesStu>> cmapstu = list3.stream()
                        .collect(Collectors.groupingBy(YxyEsbagTeachingTestQuesStu::getMark));

                Map<Integer, List<Student>> blankMap = new HashMap<Integer, List<Student>>();
                for (Integer mark : cnsList) {
                    List<YxyEsbagTeachingTestQuesStu> listStudent = cmapstu.get(mark);
                    List<Student> students = new ArrayList<Student>();
                    Student student = null;
                    if (CollectionUtils.isNotEmpty(listStudent)) {
                        for (YxyEsbagTeachingTestQuesStu yxyEsbagTeachingTestQuesStu : listStudent) {
                            if (yxyEsbagTeachingTestQuesStu.getStatus() == 1) {
                                student = new Student();
                                student.studentId = yxyEsbagTeachingTestQuesStu.getStudentId();
                                student.studentName = yxyEsbagTeachingTestQuesStu.getStudentNick();
                                student.over = yxyEsbagTeachingTestQuesStu.getIsReadOver();
                                students.add(student);
                            }
                        }
                    }
                    blankMap.put(mark, students);
                }
                model.blankMap = blankMap;

                // 计算实际总分
                Integer myMark = 0;
                for (Integer key : cnsList) {
                    // 选每一个key的总分
                    if (-1 != key) {
                        Integer size = blankMap.get(key).size();
                        Integer myMark1 = key * size;
                        myMark = myMark + myMark1;
                    }
                }
                model.blankMyMark = myMark;

                // 计算总分
                int i = 0;
                for (YxyEsbagTeachingTestQuesStu quesStu : list3) {
                    // zhiyao 未批閱
                    if (quesStu.getStatus() == 1) {
                        i++;
                    }
                }
                Integer totalMark = i * 5;
                model.blankTotalMark = totalMark;

                // 计算正确率correct(保留一位小数)
                if (totalMark != 0) {
                    double correct = ((double) myMark / (double) totalMark) * 100;
                    BigDecimal b = new BigDecimal(correct);
                    double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    model.rate = f1;
                } else {
                    model.rate = 0.0;

                }

            }

            respModels.add(model);
        }
        return respModels;

    }

    protected static class ReqModel extends YxyApiReqModel {
        // 授课包id
        public String id;
        // 题组ID
        public String quesGroupId;
        // 班级ID
        public String classId;

    }

    protected class Student {
        // 学生ID
        public String studentId;
        // 学生名称
        public String studentName;
        // 是否批阅
        public Integer over;

    }

    protected static class RespModel extends YxyApiRespModel {
        // 正确率
        public Double rate;
        // 试题难度
        public String difficultyLevel;
        // 知识点名称
        public List<String> knowledgeTexts;
        // 试题类型
        public String questionType;
        // 题干
        public Object quesBody;

        // 单选题答案
        public List<String> singleAnswer;
        // 单选题的学生作答信息
        public Map<String, List<Student>> singleMap;

        // 多选题答案
        public List<String> multiAnswer;
        // 多选题的学生作答信息
        public Map<String, List<Student>> multiMap;

        // 填空题应得总分
        public Integer blankTotalMark;
        // 填空题实得总分
        public Integer blankMyMark;
        // 填空评分
        public List<Integer> blankMark;
        // 填空题的学生的作答信息
        public Map<Integer, List<Student>> blankMap;
        // 试题ID
        public String quesId;
        // 未批阅学生信息
        public List<Student> studentsOver;

    }

}
